package com.example.mingyue.datasource;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mingyue.common.PageBean;
import com.example.mingyue.model.entity.Post;
import com.example.mingyue.model.entity.User;
import com.example.mingyue.model.vo.UserVO;
import com.example.mingyue.service.UserService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询用户资源的统一规范,搜索Es
 * username、userAccount、phone
 */
@Service
public class UserDataSource implements DataSource<UserVO>{

    @Autowired
    private UserService userService;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageBean<UserVO> doSearch(String searchText, Integer page, Integer pageSize) {


        try {
            SearchRequest request = new SearchRequest("mingyue");

            if (searchText == null || "".equals(searchText)) {
                request.source().query(QueryBuilders.matchAllQuery());
                System.out.println("上i那");
            } else {
                System.out.println(searchText);
                request.source().query(QueryBuilders.matchQuery("all", searchText));
                System.out.println("下main");
            }

            Integer pageIndex = page - 1;
            request.source().from(pageIndex).size(pageSize);

            // 4.发送请求，得到结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            PageBean<UserVO> userVOS = getPage(response);

            return userVOS;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private PageBean<UserVO> getPage(SearchResponse response) {
        // 5.解析响应结果
        SearchHits searchHits = response.getHits();
// 5.1获取总条数
        long total = searchHits.getTotalHits().value;
// 5.2获取文档数组并且遍历
        SearchHit[] hits = searchHits.getHits();


        List<UserVO> userVOList = new ArrayList<>();
        for (SearchHit hit : hits) {
            UserVO userVo = new UserVO();
            //获取文档数据源
            String json = hit.getSourceAsString();
            //反序列化
            User userVODoc = JSON.parseObject(json, User.class);
            BeanUtils.copyProperties(userVODoc,userVo);
            userVOList.add(userVo);
        }

        return new PageBean(total,userVOList);
    }
}
